﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace MMTJ
{
    internal class SymmCrypto
    {
        // Fields
        private SymmetricAlgorithm mobjCryptoService;

        // Methods
        public SymmCrypto(SymmProvEnum NetSelected)
        {
            switch (NetSelected)
            {
                case SymmProvEnum.A:
                    this.mobjCryptoService = new DESCryptoServiceProvider();
                    return;
            }
        }

        public string Decrypting(string Source, string Key)
        {
            try
            {
                byte[] bytes = Convert.FromBase64String(Source);
                Source = System.Text.Encoding.Default.GetString(bytes);
                byte[] inputByteArray = new byte[Source.Length / 2];
                for (int x = 0; x < Source.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(Source.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }
                this.mobjCryptoService.Key = ASCIIEncoding.ASCII.GetBytes(Key);
                this.mobjCryptoService.IV = ASCIIEncoding.ASCII.GetBytes(Key);

                MemoryStream stream = new MemoryStream();
                ICryptoTransform transform = this.mobjCryptoService.CreateDecryptor();
                CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write);
                stream2.Write(inputByteArray, 0, inputByteArray.Length);
                stream2.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                return System.Text.Encoding.Default.GetString(stream.ToArray());
            }
            catch
            {
                return "";
            }
        }

        public string Encrypting(string Source, string Key)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(Source);
            this.mobjCryptoService.Key = ASCIIEncoding.ASCII.GetBytes(Key);
            this.mobjCryptoService.IV = ASCIIEncoding.ASCII.GetBytes(Key);

            ICryptoTransform transform = this.mobjCryptoService.CreateEncryptor();
            MemoryStream stream = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write);
            stream2.Write(bytes, 0, bytes.Length);
            stream2.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in stream.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(ret.ToString()));
        }

        // Nested Types
        public enum SymmProvEnum
        {
            A = 0,
        }
    }
}
